// ignore_for_file: unused_import, file_names, avoid_function_literals_in_foreach_calls

import 'dart:async';
import 'dart:io';

import 'package:path/path.dart';
import 'package:path_provider/path_provider.dart';
import 'package:sqflite/sqflite.dart';
import 'package:time_manager/dict/table_dict.dart';
import 'package:time_manager/view/current/current_model.dart';

import 'RecordModel.dart';

class DataBaseRecord {
  static final DataBaseRecord _instance = DataBaseRecord.internal();
  int version = 2;
  factory DataBaseRecord() => _instance;
  DataBaseRecord.internal();

  final String tableName = 'TableRecord';
  final String columnId = 'id';
  final String title = 'title';
  final String status = 'status';
  final String duration = 'duration';
  final String time = 'createTime';

  static Database? _db;

  insert(String tableName, dynamic item) async {
    var dbClient = await db;
    var result = await dbClient.insert(tableName, item);
    // print(result);
  }

  query(String tableName,
      {int? limit,
      int? offset,
      String? orerBy,
      String? where,
      List<Object?>? whereArgs}) async {
    var dbClient = await db;
    var result = await dbClient.query(
      tableName,
      // columns: [title, status],
      where: where,
      whereArgs: whereArgs,
      limit: limit,
      orderBy: orerBy,
      offset: offset,
    );
    List<dynamic> records = [];
    if (result != null) {
      result.forEach((item) => records.add(item));
    }
    return records;
  }

  deleteData(tableName, id) async {
    var dbClient = await db;
    return await dbClient.delete(tableName, where: 'id = $id');
  }

  Future<RecoreModel> insertVideo(RecoreModel record) async {
    var dbClient = await db;
    var result = await dbClient.insert(tableName, record.toJson());
    var temp = await selectRecord(where: 'id=? ', whereArgs: [result]);
    return temp[0];
  }

  Future<List<RecoreModel>> selectRecord(
      {int? limit,
      int? offset,
      String? orerBy,
      String? where,
      List<Object?>? whereArgs}) async {
    var dbClient = await db;
    // 'uid=? and fuid=?', [6,1]   where whersArgs
    // var result = await dbClient.query('$tableName order by createTime desc');
    var result = await dbClient.query(
      tableName,
      // columns: [title, status],
      where: where,
      whereArgs: whereArgs,
      limit: limit,
      orderBy: orerBy,
      offset: offset,
    );
    List<RecoreModel> records = [];
    result.forEach((item) => records.add(RecoreModel.fromSql(item)));
    return records;
  }

  Future<int> deleteRecord(int id) async {
    var dbClient = await db;
    return await dbClient.delete(tableName, where: 'id = $id');
  }

  Future<int?> countRecord() async {
    var dbClient = await db;
    return Sqflite.firstIntValue(
        await dbClient.rawQuery('SELECT COUNT(*) FROM $tableName'));
  }

  Future<int> updateRecord(RecoreModel video) async {
    var dbClient = await db;
    return await dbClient.update(tableName, video.toJson(),
        where: "id = ${video.id}");
  }

  initDb() async {
    final path = await getDbPath();
    // 如果数据已经存在，onCreate就不会继续执行
    Database db =
        await openDatabase(path, version: version, onOpen: (db) async {
      // var temp =
      //     await db.path;

    }, onCreate: _onCreate);
    return db;
  }

  Future<String> getDbPath() async {
    // getDatabasesPath() : 获取默认数据库位置(在Android上，它通常是data/data/<package_name>/databases,在iOS上，它是Documents目录)
    // join(databasesPath, 'flashgo.db'): 相当于在上述方法获取到的位置创建了一个名为flashgo的数据库.
    // openDatabase: 按指定路径打开数据库 , 路径就是上面flash.db的路径,version为数据库版本号,onCreate是创建表的方法
    String databasesPath = await getDatabasesPath();
    // Directory aaa = await getApplicationDocumentsDirectory();
    String path = join(databasesPath, 'timeList1.db');

    //  String path=join(databasesPath,'demo.db');
    // await deleteDatabase(path);
    return path;
  }

  // 删除数据库
  deleteDb() async {
    final path = await getDbPath();
    await deleteDatabase(path);
  }

  void _onCreate(Database db, int newVersion) async {
    await db.execute('''
          create table timeList (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            time INTEGER,
            duration INTEGER,
            desc text
           )
        ''');
    await db.execute('''
          create table $tableName (
            $columnId INTEGER PRIMARY KEY AUTOINCREMENT,
            $title text,
            $time text,
            dealtime text,
            $duration text,
            $status text)
        ''');
  }

  Future<Database> get db async {
    if (_db != null) {
      return _db!;
    }
    _db = await initDb();
    // print('初始化完成');
    return _db!;
  }

  static Future<Database> get dbTool async {
    if (_db != null) {
      return _db!;
    }

    return _db!;
  }

  Future close() async {
    var dbClient = await db;
    return dbClient.close();
  }
}
